package com.k2data.k2app.service.v2;

import com.k2data.k2app.domain.po.v1.RFile;
import com.k2data.k2app.domain.po.v2.ReportPO;
import com.k2data.k2app.exception.K2ResponseException;
import com.k2data.k2app.mapper.RFileMapper;
import com.k2data.k2app.mapper.v2.ReportMapper;
import com.k2data.k2app.rest.InstanceClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.file.Paths;
import java.util.List;

/**
 * @author lidong9144@163.com 17-3-20.
 */
@Service
public class ReportService {


    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private RFileMapper rFileMapper;

    private final InstanceClient instanceClient;
    @Autowired
    public ReportService (InstanceClient instanceClient) {
        this.instanceClient = instanceClient;

    }

    /**
     * 插入客户事件
     *
     * @param po 实体
     * @return 插入 id
     * @throws K2ResponseException 客户 id 没找到, eventType 没找到
     */
    @Transactional
    public Long insert(ReportPO po) throws K2ResponseException {
        reportMapper.insertSelective(po);
        List<RFile> rFiles = RFile.updateFiles(po.getId(),po.getFileList(),"report");
        if(rFiles!=null && rFiles.size()>0){
            rFileMapper.insertBatch(rFiles);
        }
        return po.getId();
    }

    @Transactional
    public int update(ReportPO po) throws K2ResponseException {
        rFileMapper.deleteByEventId(po.getId(),"report");
        List<RFile> rFiles = RFile.updateFiles(po.getId(),po.getFileList(),"report");
        if(rFiles!=null && rFiles.size()>0){
            rFileMapper.insertBatch(rFiles);
        }
        return reportMapper.updateByPrimaryKey(po);
    }

    public List<ReportPO> list(ReportPO cond) {
        List<ReportPO> eventList = reportMapper.selectList1(cond);
        for(ReportPO event:eventList){
            //为所有文件设置文件路径
            if(event.getFileList() != null && event.getFileList().size()>0){
                List<RFile> byCustomerId = event.getFileList();
                for(RFile rFile:byCustomerId){
                    //设置文件路径
                    rFile.setFileUrl(instanceClient.getGatewayUrl() + Paths.get("/static/", rFile.getFileUrl()).toString());
                }
                event.setFileList(byCustomerId);
            }
        }
        return eventList;
    }
    public List<RFile> getFileUrls(Long id) {
        List<RFile> byCustomerId = rFileMapper.getByEventId(id,"report");
        for(RFile rFile:byCustomerId){
            rFile.setFileUrl(instanceClient.getGatewayUrl() + Paths.get("/static/", rFile.getFileUrl()).toString());
        }
        return byCustomerId;
    }

}
